import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { mockHeritageData } from '../api/mockData';

// 创建 store
export const useHeritageStore = defineStore('heritage', () => {
  // 状态
  const heritageList = ref([]);
  const regionData = ref([]);
  const currentHeritage = ref(null);
  const loading = ref(false);
  const error = ref(null);
  const filters = ref({
    category: '',
    region: '',
    level: '',
    keyword: ''
  });
  const pagination = ref({
    page: 1,
    pageSize: 10,
    total: 0
  });

  // 计算属性
  const filteredHeritageList = computed(() => {
    let result = [...heritageList.value];

    if (filters.value.keyword) {
      const keyword = filters.value.keyword.toLowerCase();
      result = result.filter(item => 
        item.name.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword)
      );
    }

    if (filters.value.category) {
      result = result.filter(item => item.category === filters.value.category);
    }

    if (filters.value.region) {
      result = result.filter(item => item.region === filters.value.region);
    }

    if (filters.value.level) {
      result = result.filter(item => item.level === filters.value.level);
    }

    return result;
  });

  const totalCount = computed(() => heritageList.value.length);

  const categories = computed(() => {
    const uniqueCategories = new Set(heritageList.value.map(item => item.category));
    return Array.from(uniqueCategories);
  });

  const regions = computed(() => {
    const uniqueRegions = new Set(heritageList.value.map(item => item.region));
    return Array.from(uniqueRegions);
  });

  const levels = computed(() => {
    const uniqueLevels = new Set(heritageList.value.map(item => item.level));
    return Array.from(uniqueLevels);
  });

  // 方法
  const setError = (message) => {
    error.value = message;
    ElMessage.error(message);
  };

  const fetchHeritageData = async () => {
    loading.value = true;
    error.value = null;

    try {
      // 使用 mock 数据
      heritageList.value = mockHeritageData;
      pagination.value.total = mockHeritageData.length;
      processRegionData();
    } catch (err) {
      const message = err.message || '获取非遗数据失败';
      setError(message);
    } finally {
      loading.value = false;
    }
  };

  const processRegionData = () => {
    const regionMap = {};
    heritageList.value.forEach(item => {
      if (!regionMap[item.region]) {
        regionMap[item.region] = {
          value: 0,
          heritageList: []
        };
      }
      regionMap[item.region].value++;
      regionMap[item.region].heritageList.push({
        name: item.name,
        category: item.category
      });
    });

    regionData.value = Object.entries(regionMap).map(([name, data]) => ({
      name,
      ...data
    }));
  };

  const getHeritageById = async (id) => {
    loading.value = true;
    error.value = null;

    try {
      // 从 mock 数据中查找
      const heritage = mockHeritageData.find(item => item.id === id);
      if (heritage) {
        currentHeritage.value = heritage;
        return heritage;
      } else {
        throw new Error('非遗项目不存在');
      }
    } catch (err) {
      const message = err.message || '获取非遗详情失败';
      setError(message);
      return null;
    } finally {
      loading.value = false;
    }
  };

  const searchHeritage = (query) => {
    if (!query) return heritageList.value;
    const lowerQuery = query.toLowerCase();
    return heritageList.value.filter(item => 
      item.name.toLowerCase().includes(lowerQuery) ||
      item.description.toLowerCase().includes(lowerQuery) ||
      item.category.toLowerCase().includes(lowerQuery)
    );
  };

  // 初始化数据
  fetchHeritageData();

  return {
    // 状态
    heritageList,
    regionData,
    currentHeritage,
    loading,
    error,
    filters,
    pagination,
    totalCount,
    // 计算属性
    filteredHeritageList,
    categories,
    regions,
    levels,
    // 方法
    fetchHeritageData,
    getHeritageById,
    searchHeritage,
    setError
  };
});